package org.example.hypersonaltools.scene;

import javafx.scene.control.ColorPicker;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import lombok.Setter;

import java.util.List;

public class ColorPalette extends Pane {
    @Setter
    private List<Region> targetRegion;  // 要修改背景的目标区域

    private final Circle[] colorCircles = new Circle[7];
    private Circle selectedCircle;
    private final Slider opacitySlider = new Slider(0, 1, 1);
    private final ColorPicker colorPicker= new ColorPicker();

    // 默认颜色方案
    private final Color[] defaultColors = {
            Color.RED, Color.ORANGE, Color.YELLOW,
            Color.GREEN, Color.BLUE, Color.INDIGO, Color.PURPLE
    };

    // 构造方法
    public ColorPalette(Orientation orientation,
                        double x, double y, double width, double height) {

        // 设置组件位置和大小
        this.setLayoutX(x);
        this.setLayoutY(y);
        this.setPrefSize(width, height);
        this.setBackground(Background.EMPTY);  // 透明背景

        // 初始化颜色圆盘
        initColorCircles(orientation);

        initColorPicker();

        // 初始化透明度滑块
        initOpacitySlider(orientation);

//        // 默认选中第一个颜色
//        selectCircle(colorCircles[0]);
    }

    private void initColorCircles(Orientation orientation) {
        double circleSize = Math.min(getPrefWidth(), getPrefHeight()) / 10;

        for (int i = 0; i < colorCircles.length; i++) {
            Circle circle = new Circle(circleSize);
            circle.setFill(defaultColors[i]);
            circle.setStroke(Color.BLACK);
            circle.setStrokeWidth(1);

            // 双击弹出拾色器
            circle.setOnMouseClicked(e -> {
                if (e.getButton() == MouseButton.PRIMARY && e.getClickCount() == 2) {
                    selectCircle(circle);
                    showColorPickerForCircle(circle);
                }else if (e.getButton() == MouseButton.PRIMARY && e.getClickCount() == 1) {
                    selectCircle(circle);
                }
            });

            colorCircles[i] = circle;
            this.getChildren().add(circle);
        }

        if (orientation == Orientation.HORIZONTAL) {
            layoutHorizontal(circleSize);
        } else {
            layoutVertical(circleSize);
        }
    }

    private void initColorPicker() {
        colorPicker.setVisible(false);
        colorPicker.setOnAction(e -> {
            Color selectedColor = colorPicker.getValue();
            if (selectedCircle != null) {
                // 保留原始颜色的透明度
                Color originalColor = (Color) selectedCircle.getFill();
                Color newColor = new Color(
                        selectedColor.getRed(),
                        selectedColor.getGreen(),
                        selectedColor.getBlue(),
                        originalColor.getOpacity()
                );

                selectedCircle.setFill(newColor);
                updateTargetRegion(newColor);
                opacitySlider.setValue(newColor.getOpacity());
            }
            colorPicker.setVisible(false);
        });
        this.getChildren().add(colorPicker);
    }

    private void showColorPickerForCircle(Circle circle) {
        // 设置拾色器初始值为当前圆盘颜色
        colorPicker.setValue((Color) circle.getFill());

        // 定位拾色器在圆盘旁边
        double pickerX = circle.getCenterX() + circle.getRadius() + 10;
        double pickerY = circle.getCenterY() - colorPicker.getHeight() / 2;

        // 确保拾色器不会超出组件边界
        if (pickerX + colorPicker.getWidth() > this.getPrefWidth()) {
            pickerX = circle.getCenterX() - circle.getRadius() - colorPicker.getWidth() - 10;
        }
        if (pickerY + colorPicker.getHeight() > this.getPrefHeight()) {
            pickerY = this.getPrefHeight() - colorPicker.getHeight();
        }

        colorPicker.setLayoutX(pickerX);
        colorPicker.setLayoutY(pickerY);
        colorPicker.setVisible(true);
        colorPicker.requestFocus();
        colorPicker.show();
    }

//    // 初始化颜色圆盘
//    private void initColorCircles(Orientation orientation) {
//        double circleSize = Math.min(getPrefWidth(), getPrefHeight()) / 10;
//
//        for (int i = 0; i < colorCircles.length; i++) {
//            Circle circle = new Circle(circleSize);
//            circle.setFill(defaultColors[i]);
//            circle.setStroke(Color.BLACK);
//            circle.setStrokeWidth(1);
//
//            // 点击事件
//            circle.setOnMouseClicked(e -> {
//                if (e.getClickCount() == 2) {
//                    //双击事件下，弹出完整拾色器,选择颜色后同步修改被选择的圆的颜色以及region颜色
//                }else {
//                    selectCircle(circle);
//                }
//
//            });
//
//            colorCircles[i] = circle;
//            this.getChildren().add(circle);
//        }
//
//        // 根据方向布局圆盘
//        if (orientation == Orientation.HORIZONTAL) {
//            layoutHorizontal(circleSize);
//        } else {
//            layoutVertical(circleSize);
//        }
//    }

    // 水平布局
    private void layoutHorizontal(double circleSize) {
        double spacing = (getPrefWidth() - colorCircles.length * circleSize * 2) / (colorCircles.length + 1);

        for (int i = 0; i < colorCircles.length; i++) {
            colorCircles[i].setCenterX(spacing + circleSize + i * (circleSize * 2 + spacing));
            colorCircles[i].setCenterY(getPrefHeight() / 3);
        }
    }

    // 垂直布局
    private void layoutVertical(double circleSize) {
        double spacing = (getPrefHeight() - colorCircles.length * circleSize * 2) / (colorCircles.length + 1);

        for (int i = 0; i < colorCircles.length; i++) {
            colorCircles[i].setCenterX(getPrefWidth() / 3);
            colorCircles[i].setCenterY(spacing + circleSize + i * (circleSize * 2 + spacing));
        }
    }

    // 初始化透明度滑块
    private void initOpacitySlider(Orientation orientation) {
        opacitySlider.setOrientation(orientation == Orientation.HORIZONTAL ?
                Orientation.HORIZONTAL: Orientation.VERTICAL);
        if (orientation == Orientation.HORIZONTAL) {
            opacitySlider.setLayoutX(getPrefWidth()-140);
            opacitySlider.setLayoutY((getPrefHeight()/3)*2);
        } else {
            opacitySlider.setLayoutX((getPrefWidth()/3)*2);
            opacitySlider.setLayoutY(getPrefHeight()-140);
        }

        opacitySlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (selectedCircle != null) {
                Color originalColor = (Color) selectedCircle.getFill();
                Color newColor = new Color(
                        originalColor.getRed(),
                        originalColor.getGreen(),
                        originalColor.getBlue(),
                        newVal.doubleValue()
                );
                selectedCircle.setFill(newColor);
                updateTargetRegion(newColor);
            }
        });

        this.getChildren().add(opacitySlider);
    }

    // 选择圆盘
    private void selectCircle(Circle circle) {
        // 重置之前选中的圆盘样式
        if (selectedCircle != null) {
            selectedCircle.setStrokeWidth(1);
        }

        // 设置新选中的圆盘
        selectedCircle = circle;
        selectedCircle.setStrokeWidth(3);  // 加粗边框表示选中

        // 更新滑块值为当前颜色的透明度
        Color color = (Color) circle.getFill();
        opacitySlider.setValue(color.getOpacity());

        // 更新目标区域颜色
        updateTargetRegion(color);
    }

    // 更新目标区域背景
    private void updateTargetRegion(Color color) {
        for (Region region : targetRegion) {
            if (region instanceof TextField textField){
                textField.setStyle("-fx-text-fill: " + color.toString().replace("0x", "#") + ";");
            }else {
                region.setBackground(new Background(new BackgroundFill(
                        color, CornerRadii.EMPTY, Insets.EMPTY
                )));
            }

        }
    }

    // 设置自定义颜色方案
    public void setCustomColors(Color[] colors) {
        if (colors.length >= colorCircles.length) {
            for (int i = 0; i < colorCircles.length; i++) {
                colorCircles[i].setFill(colors[i]);
            }
        }
    }

}